<script setup>
import { addCollegeApi, collegeListQueryApi, deleteCollegeApi, getCollegeApi } from '@/api/baseData'
import { updateUserStatusApi } from '@/api/user'
import Form from '@/components/User/Form.vue'
import FormAdd from '@/components/common/formAdd.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/common/table.vue'
import { dayFormat } from '@/utils/common/dayjs'
import { bus } from '@/utils/common/mitt'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { utils, writeFileXLSX } from 'xlsx'
import Password from '../Personal/password.vue'
import { addAdminApi } from '@/api/job'

// 获取年份
const yearData = new Date().getFullYear()
const router = useRouter()

// 常量定义
const FORM_MODEL = [
  {
    prop: 'college',
    label: '学院',
    type: 'selectCollege'
  }
]

const BUTTON_OPTIONS = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '新增',
    btnType: 'success',
    prop: 'add'
  },
  {
    name: '导出',
    btnType: 'warning',
    prop: 'output'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  }
]

const STUDENT_FORM_OPTIONS = [
  {
    label: '学院',
    type: 'input',
    prop: 'college'
  }
]
const STUDENT_FORM_Edit_OPTIONS = [
  {
    label: '学院',
    type: 'input',
    prop: 'college',
    disabled:true
  },
  {
    label: '学院管理员账号',
    type: 'input',
    prop: 'account'
  },
  {
    label: '密码',
    type: 'input',
    prop: 'password'
  },
]

const STUDENT_BUTTON_OPTIONS = [
  {
    name: '取消',
    btnType: '',
    prop: 'cancel'
  },
  {
    name: '确定',
    btnType: 'success',
    prop: 'confirm'
  }
]
const STUDENT_BUTTON_Edit_OPTIONS = [
  {
    name: '取消',
    btnType: '',
    prop: 'cancel'
  },
  {
    name: '确定',
    btnType: 'success',
    prop: 'edit'
  }
]

const TABLE_COLUMNS = [
  {
    prop: 'college',
    label: '学院'
  },
  {
    prop: 'count',
    label: '学院人数'
  },
  {
     prop: 'account',
    label: '学院管理员账号'
  }
]

const TABLE_OPTIONS = [
  {
    label: '修改',
    type: 'warning',
    prop: 'edit'
  },
  {
    label: '删除',
    type: 'danger',
    prop: 'delete'
  }
]

const EXCEL_HEADERS = ['序号', '学院', '学院人数']

// 响应式数据
const dialogFormVisible = ref(false)
const formData = ref({ college: '' })
const formEditData = ref({ college: '',account: '' ,password: '' })
const form = ref({ college: '' })
const tableData = ref([])
const pagizationTotal = ref(0)
const formRef = ref(null)
const pagizationRef = ref(null)
const selectFormRef = ref(null)

// 获取表格数据
async function getCollegeData(params = {}) {
  const res = await collegeListQueryApi(params)
  tableData.value = res.data
  pagizationTotal.value = res.total
}

// 导出Excel
async function exportToExcel() {
  const { data } = await collegeListQueryApi()
  console.log(data);
  
  
  const sheetData = data.map((item, index) => ({
    index: index + 1,
    college: item.college,
    count: item.count
  }))

  const worksheet = utils.json_to_sheet(sheetData)
  const workbook = utils.book_new()
  
  utils.book_append_sheet(workbook, worksheet, 'Data')
  utils.sheet_add_aoa(worksheet, [EXCEL_HEADERS], { origin: 'A1' })
  
  writeFileXLSX(workbook, `${dayFormat(new Date())}导出数据.xlsx`)
}

// 表单操作处理
async function handleFormOperation(type, data) {
  const operationMap = {
    query: async () => {
      const res = await collegeListQueryApi(data)
      showStatusMessage(res)
      tableData.value = res.data
      pagizationTotal.value = res.total
    },
    add: () => { dialogFormVisible.value = true },
    output: exportToExcel,
    cancel: () => {
      formRef.value.reset()
      dialogFormVisible.value = false
    },
    confirm: async () => {
      const res = await addCollegeApi({ ...data, time: dayFormat(new Date()) })
      showStatusMessage(res)
      getCollegeData()
      bus.emit('delete')
      dialogFormVisible.value = false
    },
    reset: () => {
      getCollegeData()
      pagizationRef.value.reset()
      selectFormRef.value.reset()
    },
    edit: async () => {
     console.log(data);
     let info={
      college:data.college,
      account:data.account,
      password:data.password
    }
     const res=await addAdminApi(info)
     showStatusMessage(res)
     getCollegeData()
     formEditData.value={}
     dialogFormEdit.value=false
    }
  }

  if (operationMap[type]) {
    await operationMap[type]()
  }
}
const dialogFormEdit = ref(false)
// 表格操作处理
async function handleTableOperation(data, type) {
  // console.log(data,type);
  
  const operationMap = {
    switch: async () => {
      const res = await updateUserStatusApi({ 
        account: data.account, 
        status: data.status 
      })
      showStatusMessage(res)
    },
    delete: async () => {
      const res = await deleteCollegeApi(data)
      showStatusMessage(res)
      getCollegeData()
      bus.emit('delete')
    },
    edit: () => {
      formEditData.value.college=data.college
     
      
      dialogFormEdit.value = true
    }
  }

  if (operationMap[type]) {
    await operationMap[type]()
  }
}

// 分页处理
function handleSizeChange(val) {
  getCollegeData({ size: val })
  pagizationRef.value.reset()
}

function handleCurrentChange(page, size) {
  getCollegeData({ page, size })
}

// 初始化
getCollegeData()
</script>

<template>
  <div class="user-wrapper">
    <div class="user-content">
      <Form
        :data="formData"
        :formOpt="FORM_MODEL"
        :btnOpt="BUTTON_OPTIONS"
        @handleForm="handleFormOperation"
        ref="selectFormRef"
      />
      
      <Table
        :tableData="tableData"
        :columns="TABLE_COLUMNS"
        :options="TABLE_OPTIONS"
        @handleTable="handleTableOperation"
      >
        <template #firstColumn>
          <el-table-column type="index" label="序号" width="100" align="center" />
        </template>
      </Table>
      
      <Pagization
        ref="pagizationRef"
        :total="pagizationTotal"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      title="新增学院"
      width="500"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <FormAdd
        ref="formRef"
        :data="form"
        :formOpt="STUDENT_FORM_OPTIONS"
        :btnOpt="STUDENT_BUTTON_OPTIONS"
        @handleForm="handleFormOperation"
      />
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      v-model="dialogFormEdit"
      title="修改学院"
      width="500"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <FormAdd
        ref="formRef"
        :data="formEditData"
        :formOpt="STUDENT_FORM_Edit_OPTIONS"
        :btnOpt="STUDENT_BUTTON_Edit_OPTIONS"
        @handleForm="handleFormOperation"
      />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  .user-content {
    width: 100%;
    padding: 30px 50px;
    text-align: left;
    overflow: auto;
  }
}
</style>
